package com.tencent.welink.util;

import com.tencent.welink.config.BussinessConfig;
import io.netty.buffer.ByteBuf;

import java.util.Arrays;

/**
 * Created by junchihe on 2019/5/9.
 */
public class ByteEncrypt {

    byte[] head ;
    byte[] full;
    boolean encrypted = false;
    private final IEncryptAndDecrypt aes128;

    public void freeData(){
        head = null;
        full = null;
    }


    public ByteEncrypt(final IEncryptAndDecrypt aes128) {
        this.aes128 = aes128;
    }

    public void buildData(byte[] data) {
        head = null;
        full = null;
        encrypted = false;
        if(aes128 != null  && data.length > BussinessConfig.encyrptingbyteslen) {
            byte[] headTemp = Arrays.copyOfRange(data,0,BussinessConfig.encyrptingbyteslen);
            full = data;
            head = aes128.encrypt(headTemp);
            if(head != null) {
                encrypted = true;
            } else {
                head = data;
                full = null;
            }

        } else {
            head = data;
            full = null;
        }
    }

    public void testZero(byte[] head,int keyFrame) {
        if(head!= null) {
            for (int i=0;i<head.length;i++){
                if(i<4){
                    if(i<2)
                        head[i] = 0;
                    if(i==2) {
                        head[i] = 1;
                    }
                    if(i==3 && keyFrame==1){
                        head[i] = 0x65;
                    } else if(i==3 && keyFrame !=1) {
                        head[i] = 0x61;
                    }

                }
            }
        }
    }

    public int getEncryptedLength() {
        if(encrypted) {
            return head.length ;
        } else {
            return 0;
        }
    }

    public int getLength() {
        int len = 0;
        if(encrypted){
            len = head.length + full.length-BussinessConfig.encyrptingbyteslen; //+ separator.length +
        } else{
            len = head.length;
        }
        return len;
    }

    public void writeData(ByteBuf bf) {
        bf.writeBytes(head);
        if(encrypted) {
            //bf.writeBytes(separator);
            bf.writeBytes(full,BussinessConfig.encyrptingbyteslen,full.length-BussinessConfig.encyrptingbyteslen);
        }
    }

}
